<template>
  <div class="login-container">
    <div class="login-box">
      <h2>欢迎登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名">
            <template #prefix><el-icon><User /></el-icon></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" show-password>
            <template #prefix><el-icon><Lock /></el-icon></template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        还没有账号？<router-link to="/register">立即注册</router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'LoginPage',
  components: { User, Lock },
  setup() {
    const router = useRouter()
    const loginFormRef = ref(null)
    const loading = ref(false)

    const loginForm = reactive({ username: '', password: '' })

    const rules = { /* 保持原有规则不变 */ }

    const handleLogin = async () => {
      try {
        await loginFormRef.value.validate()
      } catch {
        return
      }

      try {
        loading.value = true
        const { data } = await axios.post('http://localhost:8080/auth/login', loginForm)

        if (data) {  // 根据实际返回结构调整
          localStorage.setItem('user', JSON.stringify(data))
          ElMessage.success('登录成功')
          router.push('/main')
        }
      } catch (error) {
        // 处理400错误响应
        if (error.response?.status === 400) {
          ElMessage.error(error.response.data || '用户名或密码错误')
        } else {
          // 处理其他类型错误
          const errorMessage = error.message || '网络连接异常，请稍后重试'
          ElMessage.error(errorMessage)
        }
      } finally {
        loading.value = false
      }
    }

    return { loginFormRef, loading, loginForm, rules, handleLogin }
  }
}
</script>
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
}

.login-button {
  width: 100%;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.register-link a {
  color: #409EFF;
}
</style>
